package org.mspring.mlog.web.freemarker.directive;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.mspring.platform.qiniu.QiniuImageStyleUtils;
import org.mspring.platform.web.freemarker.DirectiveUtils;
import org.mspring.platform.web.freemarker.directive.AbstractDirectiveModel;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 获取图片的展示URL
 *
 * @author Gao Youbo
 * @since 2013-6-4
 */
public class PhotoUrlDirectiveModel extends AbstractDirectiveModel {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void exec(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String url = DirectiveUtils.getString("url", params);
        if (StringUtils.isBlank(url)) {
            env.getOut().append("404");
        } else {
            String style = DirectiveUtils.getString("style", params);
            if (StringUtils.isNotBlank(style)) {
                url = QiniuImageStyleUtils.generateByStyleName(url, style);
                env.getOut().append(url);
                return;
            }
            int width = DirectiveUtils.getIntValue("width", params, 0);
            int height = DirectiveUtils.getIntValue("height", params, 0);
            width = width < 0 ? 0 : width;
            height = height < 0 ? 0 : height;
            if (width == 0 && height == 0) {
                env.getOut().append(url);
            } else {
                url = QiniuImageStyleUtils.generateByImageView(url, width, height);
                env.getOut().append(url);
            }
        }
    }
}
